﻿using System;
using System.Globalization;
using System.Text;

namespace Firefly.ExtensionMethods
{
    public static class StringExtensions
    {
        public static byte[] ToHexByteArray(this string obj)
        {
            // Odd length strings are not valid.
            if ((obj.Length % 2) != 0)
            {
                return null;
            }

            try
            {
                byte[] byteArray = new byte[obj.Length / 2];

                for (int offset = 0; offset < obj.Length; offset += 2)
                {
                    string substring = obj.Substring(offset, 2);
                    byteArray[offset / 2] = byte.Parse(substring, NumberStyles.HexNumber);
                }

                return byteArray;
            }
            catch (FormatException)
            {
                return null;
            }
            catch (OverflowException)
            {
                return null;
            }
            catch (ArgumentOutOfRangeException)
            {
                return null;
            }
        }

        public static byte[] SerializeBigEndian(this string obj)
        {
            byte[] tempArray = (new UnicodeEncoding(true, false)).GetBytes(obj);
            return tempArray;
        }

        public static byte[] SerializeBigEndian(this string obj, int blockLength)
        {
            byte[] tempArray = (new UnicodeEncoding(true, false)).GetBytes(obj);
            byte[] tempBlock = new byte[blockLength];
            Array.Copy(tempArray, tempBlock, tempArray.Length);
            return tempBlock;
        }

        public static T ToEnum<T>(this string obj)
        {
            return (T)Enum.Parse(typeof(T), obj);
        }
    }
}